<?php

namespace src\controller;

use PDO;
use src\core\Database;



class LoginController
{
    private $pdo;

    public function __construct()
    {
        session_start(); // 启动会话
        //创建 Database 实例并获取数据库连接
        $db = new Database();
        $this->pdo = $db->getConnection();
    }

    public function login()
    {
        //检查请求方法是否为 POST
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            //获取表单数据
            $username = $_POST['username'];
            $password = $_POST['password'];

            // 查询用户是否存在
            $stmt = $this->pdo->prepare('SELECT * FROM users WHERE username = :username');
            $stmt->execute(['username' => $username]);
            $user = $stmt->fetch(PDO::FETCH_ASSOC);

            // 验证用户名和密码
            if ($user && $password === $user['password']) {
                // 登录成功，设置会话
                $_SESSION['user_id'] = $user['id'];
                $_SESSION['username'] = $user['username'];

                header('Location: index.php');
                exit;
            } else {
                // 登录失败
                $error = "用户名或密码错误";
            }
        }
        include __DIR__ . '/../views/login.view.php';
    }

    public function checkLogin(){
        if (!isset($_SESSION['user_id'])){
            header('Location: http://localhost/hospital_department/login.php');
            exit;
        }
    }

    public function logout()
    {
        //启动会话
        session_start();

//销毁所有的会话
        $_SESSION = array();//清空会话变量
        session_destroy();//销毁会话

//重定向到登录页面
        header('Location: login.php');
        exit();
    }
}
?>